<?php
/**
 * Created by PhpStorm.
 * User: lihouse
 * Date: 2017/5/2
 * Time: 1:57
 */

namespace common\services;


use common\models\Config;
use Yii;

class ConfigSve extends BaseSve
{
    /**
     * 更新配置
     * @param array $data
     * @param string $scenario
     * @return array
     */
    public function update(array $data, string $scenario = ''):array
    {
        $db = Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            foreach ($data as $key => $value) {
                $Config = Config::findOne(['config_name' => $key]);
                if (empty($Config)) {
                    //空值跳过
                    continue;
                }
                //修改值
                $Config->config_value = $value;
                //检查错误
                self::checkErr($Config);
                $rs = $Config->update();
                if ($rs === false) {
                    throw new \Exception('修改 ' . $Config->remark . ' 失败', -1);
                }
            }
            $transaction->commit();
            return self::result('保存成功', 0);
        } catch (\Exception $e) {
            $transaction->rollBack();
            if (array_key_exists($e->getCode(), OC_ERR_CODE)) {
                return self::result($e->getMessage(), $e->getCode());
            } else {
                return self::result('系统繁忙', -50);
            }
        }
    }
}